package com.yjz.controller;

import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.admin.indices.create.CreateIndexResponse;
import org.elasticsearch.action.admin.indices.delete.DeleteIndexResponse;
import org.elasticsearch.action.admin.indices.mapping.put.PutMappingRequest;
import org.elasticsearch.action.admin.indices.mapping.put.PutMappingResponse;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.search.SearchType;
import org.elasticsearch.client.Requests;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.util.Date;

import static org.elasticsearch.common.xcontent.XContentFactory.jsonBuilder;

@RestController
@RequestMapping(value = "/api")
@Slf4j
public class TestController {
  //todo 待撤回
//	@Autowired
  private TransportClient client;

  @RequestMapping(value = "/test", produces = "application/json; charset=UTF-8", method = RequestMethod.GET)
  public String test() {
    log.info("helloWorld");
    return "helloWorld";
  }


  /**
   * @description:指定索引名,创建非结构化索引
   * @author :yuanJinZhong
   * @date :2018/8/29-11:30
   */
  @RequestMapping(value = "/addIndexSpecificName", produces = "application/json; charset=UTF-8", method = RequestMethod.GET)
  public String addIndexSpecificName(@RequestParam(name = "indexName") String indexName) throws IOException {
    CreateIndexResponse response = client.admin().indices().prepareCreate(indexName).get();
    log.info("添加索引响应结果:{}", response.toString());
    return response.toString();
  }


  /**
   * @description:指定索引名,和类型，创建结构化索引 并给指定的field设置中文分词, 在这之前 索引 必须先创建好
   * @author :yuanJinZhong
   * @date :2018/8/29-11:30
   */
  @RequestMapping(value = "/addMappingIndexSpecificName", produces = "application/json; charset=UTF-8", method = RequestMethod.GET)
  public String addMappingIndexSpecificName(@RequestParam(name = "indexName") String indexName, @RequestParam(name = "type") String type) throws IOException {

//		索引名:
    indexName = "employee";
//		类型名:
    type = "Product_technology_center";

    /*构建结构化索引mapping*/
    XContentBuilder builder = jsonBuilder()
      .startObject()
      .startObject("properties")
      .startObject("name").field("type", "text").field("analyzer", "ik_max_word").endObject()
      .startObject("work_address ").field("type", "text").field("analyzer", "ik_max_word").endObject()
      .startObject("home_address").field("type", "text").field("analyzer", "ik_max_word").endObject()
      .startObject("phone").field("type", "text").field("analyzer", "ik_max_word").endObject()
      .startObject("position").field("type", "text").field("analyzer", "ik_max_word").endObject()
      .startObject("job_description").field("type", "text").field("analyzer", "ik_max_word").endObject()
      .endObject()
      .endObject();

    /*创建:构建结构化索引mapping 的请求*/
    PutMappingRequest putMappingRequest = Requests.putMappingRequest(indexName).source(builder).type(type);

    /*指定索引添加结构化映射*/
    PutMappingResponse response = client.admin().indices().putMapping(putMappingRequest).actionGet();

    log.info("添加索引响应结果:{}", response.isAcknowledged());

    return response.isAcknowledged() + "";
  }


  /**
   * @description:往指定索引里面添加文档 请求样式：?index=employee&type=Product_technology_center&id=2
   * @author :yuanJinZhong
   * @date :2018/8/29-15:19
   */
  @RequestMapping(value = "/addDocToSpecialIndex", produces = "application/json; charset=UTF-8", method = RequestMethod.GET)
  public String addDocToSpecialIndex(@RequestParam(value = "index") String index, @RequestParam(value = "type") String type, @RequestParam(value = "id") String id) throws IOException {
    XContentBuilder builder = jsonBuilder()
      .startObject()
      .field("name", "李鑫运")
      .field("work_address", "中成智谷C4-9")
      .field("home_address", "殷高西路2222号")
      .field("phone", "15266667785")
      .field("position", "java开发工程师")
      .field("job_description", "主要负责结算系统,财务系统,车后市场等系统的研发")
      .endObject();
    IndexResponse response = client.prepareIndex(index, type, id)
      .setSource(builder)
      .get();
    log.info(response.getResult().toString());

    return response.getResult().toString();
  }


  /**
   * @description:指定索引名,删除索引
   * @author :yuanJinZhong
   * @date :2018/8/29-11:30
   */
  @RequestMapping(value = "/deleteIndexSpecificName", produces = "application/json; charset=UTF-8", method = RequestMethod.GET)
  public String deleteIndexSpecificName(@RequestParam(name = "indexName") String indexName) throws IOException {
    DeleteIndexResponse response = client.admin().indices().prepareDelete(indexName).get();
    log.info("添加索引响应结果:{}", response.isAcknowledged());
    return response.isAcknowledged() + "";
  }


  /**
   * @description:创建非结构化索引文档
   * @author :yuanJinZhong
   * @date :2018/8/29-11:30
   */
  @RequestMapping(value = "/addIndex", produces = "application/json; charset=UTF-8", method = RequestMethod.GET)
  public void addEsIndex() throws IOException {
    IndexResponse response = client.prepareIndex("shopping", "goods", "2").setSource(jsonBuilder()
      .startObject()
      .field("projectName", "web端电商项目")
      .field("source", "物流tms")
      .field("createdate", new Date())
      .endObject()
    ).get();

    log.info("添加索引响应结果:{}", response.toString());

  }

  /**
   * @description: 搜索索引库
   * @author :yuanJinZhong
   * @date :2018/8/28-10:54
   */
  @RequestMapping(value = "/search", produces = "application/json; charset=UTF-8", method = RequestMethod.GET)
  public String serarch(@RequestParam(value = "keyWord") String keyWord) {
    SearchResponse response = client.prepareSearch("employee")
      .setTypes("Product_technology_center")
      .setSearchType(SearchType.DFS_QUERY_THEN_FETCH)
      /**
       * 说明：source字段值是：物流tms 但是下面搜索:"物流" 时 是查不到数据的，因为es默认的分词器把"物流tms" 分成"物","流","tms"
       * 所以汉字只能单独查, 这时候需要修改 es的中文分词器
       */
      .setQuery(QueryBuilders.termQuery("job_description", keyWord)).get();
    return response.toString();
  }

  /**测试中文分词是否管用
   *http://192.168.59.128:9200/employee/_analyze    (post方式  指定索引调用_analyze方法)
   *
   * requestbody: {"field":"job_description","text":"ElasticSearch是一个基于Lucene的搜索服务器。
   * 它提供了一个分布式多用户能力的全文搜索引擎，基于RESTful web接口。Elasticsearch是用Java开发的，作为当前流行的企业级搜索引擎，
   * 用于云计算中，能够达到实时搜索，并且具有稳定，可靠，快速安装，使用方便等多种优点，得到大多数企业的青睐。"}

   */


}
